package data_treating

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"goocr/util"
	"net/http"
	"os"
	"time"
)

func init() {
	//初始化路由
	go func() {
		ser := InitRouter()
		if err := ser.Run(":5100"); err != nil {
			os.Exit(-1)
		} else {
			util.LogInfo(fmt.Sprintf("service running in %d\n", 5100))
		}
	}()
}

func InitRouter() *gin.Engine {
	engine := gin.Default()
	// 加载 HTML 模板文件
	engine.LoadHTMLGlob("templates/*")
	engine.GET("/rankingList/:nType", RankingList) //排行榜
	engine.GET("/delDb", DelDb)                    //清空数据库
	return engine
}

type Ranking struct {
	Ranking   int    `json:"ranking"`
	UserId    int64  `json:"userId"`
	NickName  string `json:"nickName"`
	TotalMark int64  `json:"totalMark"`
}

// 排行榜
func RankingList(c *gin.Context) {
	nType := c.Param("nType")
	data, err := RankingData(nType)
	if err != nil {
		Failure(c, err)
		return
	}
	c.HTML(http.StatusOK, "ranking_list.html", gin.H{
		"data": data,
	})
}

func RankingData(nType string) (res []Ranking, err error) {
	startTime, endTime := getInterval(nType)
	param := &QueryParam{
		GetUnix(fmt.Sprintf("%s%s", startTime, " 00:00:00")),
		GetUnix(fmt.Sprintf("%s%s", endTime, " 23:59:59")),
	}
	lists, err := param.Query()
	if err != nil {
		return
	}
	res = make([]Ranking, 0)
	for i, list := range lists {
		res = append(res, Ranking{
			Ranking:   i + 1,
			UserId:    list.UserId,
			NickName:  list.NickName,
			TotalMark: list.Score,
		})
	}
	return
}

// 获取这周，上周，上月时间间隔
func getInterval(nType string) (startTime, endTime string) {
	now := time.Now()
	offset := int(time.Monday - now.Weekday())
	if offset > 0 {
		offset = -6
	}
	switch nType {
	case "1":
		startTime = now.Format(DateFormat)
		endTime = now.Format(DateFormat)
	case "2":
		startTime = now.AddDate(0, 0, offset).Format(DateFormat)
		endTime = now.AddDate(0, 0, offset+6).Format(DateFormat)
	case "3":
		startTime = now.AddDate(0, 0, offset-7).Format(DateFormat)
		endTime = now.AddDate(0, 0, offset-1).Format(DateFormat)
	case "4":
		startTime = now.AddDate(0, -1, offset*7).Format(DateFormat)
		endTime = now.AddDate(0, 0, offset*7).Format(DateFormat)
	}
	return
}

func Failure(c *gin.Context, err error) {
	data := &RespBody{
		Code:    http.StatusInternalServerError,
		Message: fmt.Sprintf("%v", err),
	}
	c.JSON(http.StatusInternalServerError, data)
}

type RespBody struct {
	/**
	状态码
	*/
	Code int `json:"code"`
	/**
	响应信息
	*/
	Message string `json:"message"`
	/**
	响应结果数据
	*/
	Data interface{} `json:"data"`
}

// 获取该日期时间的时间戳
func GetUnix(timeStr string) int64 {
	//设置时区
	var LOC, err = time.LoadLocation("Asia/Shanghai")
	if err != nil {
		LOC = time.FixedZone("CST", 8*3600)
	}
	//解析日期时间字符串
	tim, _ := time.ParseInLocation("2006-01-02 15:04:05", timeStr, LOC)
	//获取该日期时间的时间戳
	return tim.Unix()
}

// 清空数据库
func DelDb(c *gin.Context) {
	if err := Delete(); err != nil {
		Failure(c, err)
		return
	}
	c.HTML(http.StatusOK, "db.html", nil)
}
